<template>
  <VTable ref="tableRef" v-bind="tableOptins" @resetAndQuery="resetAndQuery">
    <template #form="{ form }">
      <div>
        <el-date-picker
          v-model="form.time"
          type="week"
          format="YYYY 第 ww 周"
          value-format="YYYY-MM-DD"
          @change="handleTimeChange"
          placeholder="选择周"
        />
      </div>
    </template>
    <template #week0Header="{ row }">
      <div class="text-center">
        <div>{{ `W${weekInfo[0].weekNumber}` }}</div>
        <div>{{ `${weekInfo[0].startOfWeek} - ${weekInfo[0].endOfWeek}` }}</div>
        <div>( 计划 | 实际 )</div>
      </div>
    </template>
    <template #week0Default="{ row }">
      <div class="text-center">
        {{ row?.scheduleAmountweek0 || "-" }}|{{
          row?.actualAmountweek0 || "-"
        }}
      </div>
    </template>
    <template #week1Header="{ row }">
      <div class="text-center">
        <div>{{ `W${weekInfo[1].weekNumber}` }}</div>
        <div>{{ `${weekInfo[1].startOfWeek} - ${weekInfo[1].endOfWeek}` }}</div>
        <div>( 计划 | 实际 )</div>
      </div>
    </template>
    <template #week1Default="{ row }">
      <div class="text-center">
        {{ row?.scheduleAmountweek1 || "-" }}|{{
          row?.actualAmountweek1 || "-"
        }}
      </div>
    </template>
    <template #week2Header="{ row }">
      <div class="text-center">
        <div>{{ `W${weekInfo[2].weekNumber}` }}</div>
        <div>{{ `${weekInfo[2].startOfWeek} - ${weekInfo[2].endOfWeek}` }}</div>
        <div>( 计划 | 实际 )</div>
      </div>
    </template>
    <template #week2Default="{ row }">
      <div class="text-center">
        {{ row?.scheduleAmountweek2 || "-" }}|{{
          row?.actualAmountweek2 || "-"
        }}
      </div>
    </template>
    <template #week3Header="{ row }">
      <div class="text-center">
        <div>{{ `W${weekInfo[3].weekNumber}` }}</div>
        <div>{{ `${weekInfo[3].startOfWeek} - ${weekInfo[3].endOfWeek}` }}</div>
        <div>( 计划 | 实际 )</div>
      </div>
    </template>
    <template #week3Default="{ row }">
      <div class="text-center">
        {{ row?.scheduleAmountweek3 || "-" }}|{{
          row?.actualAmountweek3 || "-"
        }}
      </div>
    </template>
    <template #week4Header="{ row }">
      <div class="text-center">
        <div>{{ `W${weekInfo[4].weekNumber}` }}</div>
        <div>{{ `${weekInfo[4].startOfWeek} - ${weekInfo[4].endOfWeek}` }}</div>
        <div>( 计划 | 实际 )</div>
      </div>
    </template>
    <template #week4Default="{ row }">
      <div class="text-center">
        {{ row?.scheduleAmountweek4 || "-" }}|{{
          row?.actualAmountweek4 || "-"
        }}
      </div>
    </template>
  </VTable>
  <Remark
    v-model="remarkVisible"
    title="备注信息"
    url="fundScheduleRemark"
    :remarkData="remarkData"
    :data="remarkValue"
    @refresh="refresh"
    @close="(remarkData = {}), (remarkValue = '')"
  />
</template>
<script lang="jsx" setup>
import { ElMessage } from "element-plus";
import { getWeekInfo } from "@/utils/time.js";
import { transformData } from "@/utils/tools.js";
import {
  getWeekFundScheduleSummary,
  updateFundScheduleRemark,
} from "../../api.js";
import { Edit } from "@element-plus/icons-vue";
import Remark from "@/components/remark/index.vue";
let weekInfo = [];
const weeksOffsetArray = [-1, 0, 1, 2, 3];
function getTodayTime() {
  weeksOffsetArray.forEach((offset, index) => {
    weekInfo.push(getWeekInfo(offset));
  });
}
getTodayTime();
const tableRef = ref();
const handleTimeChange = (val) => {
  weekInfo = [];
  weeksOffsetArray.forEach((offset, index) => {
    weekInfo.push(getWeekInfo(offset, val));
  });
  tableRef.value?.$table.commitProxy("reload");
  nextTick(async () => {
    await tableRef.value?.$table.reloadColumn(tableOptins.columns);
  });
};
const tableOptins = reactive({
  formConfig: {
    data: {
      time: weekInfo?.[1]?.startOfWeek || "",
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    {
      title: "类别",
      field: "category",
      width: 100,
    },
    {
      title: "项目",
      field: "fundItem",
      width: 100,
    },
    {
      title: "WK18",
      field: "todo",
      width: 215,
      slots: {
        header: "week0Header",
        default: "week0Default",
      },
    },
    {
      title: "差异额/差异率",
      width: 150,
      slots: {
        default: ({ row }) => {
          return (
            <div class="text-center">
              {row?.diffAmountweek0 || "-"}|{row?.diffRatioweek0 || "-"}
            </div>
          );
        },
      },
    },
    {
      title: "备注信息",
      field: "remarkweek0",
      minWidth: 150,
      slots: {
        default: ({ row }) => {
          return (
            <div
              onClick={() =>
                handleRemark(row, row.diffRatioweek0, "0", row.remarkweek0)
              }
            >
              <el-button type="primary" link icon={Edit} />
              <el-link type="primary">{row.remarkweek0}</el-link>
            </div>
          );
        },
      },
      line: 2,
    },
    {
      title: "WK19(本周)",
      field: "todo",
      width: 215,
      slots: {
        header: "week1Header",
        default: "week1Default",
      },
    },
    {
      title: "差异额/差异率",

      width: 150,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row?.diffAmountweek1 || "-"}|{row?.diffRatioweek1 || "-"}
            </div>
          );
        },
      },
    },
    {
      title: "备注信息",
      field: "remarkweek1",
      minWidth: 150,
      slots: {
        default: ({ row }) => {
          return (
            <div
              onClick={() =>
                handleRemark(row, row.diffRatioweek1, "1", row.remarkweek1)
              }
            >
              <el-button type="primary" link icon={Edit} />
              <el-link type="primary">{row.remarkweek0}</el-link>
            </div>
          );
        },
      },
      line: 2,
    },
    {
      title: "WK20",
      field: "todo",
      width: 215,
      slots: {
        header: "week2Header",
        default: "week2Default",
      },
    },
    {
      title: "差异额/差异率",
      width: 150,
      slots: {
        default: ({ row }) => {
          return (
            <div class="text-center">
              {row?.diffAmountweek2 || "-"}|{row?.diffRatioweek2 || "-"}
            </div>
          );
        },
      },
    },
    {
      title: "备注信息",
      field: "remarkweek2",
      minWidth: 150,
      slots: {
        default: ({ row }) => {
          return (
            <div
              onClick={() =>
                handleRemark(row, row.diffRatioweek2, "2", row.remarkweek2)
              }
            >
              <el-button type="primary" link icon={Edit} />
              <el-link type="primary">{row.remarkweek0}</el-link>
            </div>
          );
        },
      },
      line: 2,
    },
    {
      title: "WK21",
      field: "todo",
      width: 215,
      slots: {
        header: "week3Header",
        default: "week3Default",
      },
    },
    {
      title: "差异额/差异率",
      width: 150,
      slots: {
        default: ({ row }) => {
          return (
            <div class="text-center">
              {row?.diffAmountweek3 || "-"}|{row?.diffRatioweek3 || "-"}
            </div>
          );
        },
      },
    },
    {
      title: "备注信息",
      field: "remarkweek3",
      minWidth: 150,
      slots: {
        default: ({ row }) => {
          return (
            <div
              onClick={() =>
                handleRemark(row, row.diffRatioweek3, "3", row.remarkweek3)
              }
            >
              <el-button type="primary" link icon={Edit} />
              <el-link type="primary">{row.remarkweek0}</el-link>
            </div>
          );
        },
      },
      line: 2,
    },
    {
      title: "WK22",
      field: "todo",
      width: 215,
      slots: {
        header: "week4Header",
        default: "week4Default",
      },
    },
    {
      title: "差异额/差异率",
      width: 150,
      slots: {
        default: ({ row }) => {
          return (
            <div class="text-center">
              {row?.diffAmountweek4 || "-"}|{row?.diffRatioweek4 || "-"}
            </div>
          );
        },
      },
    },
    {
      title: "备注信息",
      field: "remarkweek4",
      minWidth: 150,
      slots: {
        default: ({ row }) => {
          return (
            <div
              onClick={() =>
                handleRemark(row, row.diffRatioweek4, "4", row.remarkweek4)
              }
            >
              <el-button type="primary" link icon={Edit} />
              <el-link type="primary">{row.remarkweek0}</el-link>
            </div>
          );
        },
      },
      line: 2,
    },
  ],
  proxyConfig: {
    props: {
      result: "data",
    },
    autoLoad: false,
    ajax: {
      query: ({ form }) => {
        let params = {
          start: `${weekInfo[0].year}W${weekInfo[0].weekNumber}`,
          end: `${weekInfo[weekInfo.length - 1].year}W${
            weekInfo[weekInfo.length - 1].weekNumber
          }`,
        };
        // let params = transformData(form);
        return getWeekFundScheduleSummary({ ...params }).then((res) => {
          let list = getList(res.data);
          return {
            data: list,
          };
        });
      },
    },
  },
});
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
const getList = (data) => {
  const { paymentWeekItems, receivableWeekItems } = data;
  const processWeekItems = (items, category) => {
    return items?.map((item) => {
      const newItem = { category };
      weekInfo.forEach((it, ind) => {
        const str = `${it.year}W${it.weekNumber}`;
        const week = item?.details?.find((i) => i.weekPeriod == str);
        const prefix = `week${ind}`;
        if (week) {
          newItem[`actualAmount${prefix}`] = week.actualAmount;
          newItem[`diffAmount${prefix}`] = week.diffAmount;
          newItem[`diffRatio${prefix}`] = week.diffRatio;
          newItem[`remark${prefix}`] = week.remark;
          newItem[`scheduleAmount${prefix}`] = week.scheduleAmount;
        }
      });
      let newObj = Object.assign({}, newItem, item);
      return newObj;
    });
  };

  const paymentWeek = processWeekItems(paymentWeekItems, "资金流出");
  const receivableWeek = processWeekItems(receivableWeekItems, "资金流入");
  let arr = [...receivableWeek, ...paymentWeek];
  return arr;
};
const remarkVisible = ref(false);
const remarkData = ref({});
const remarkValue = ref(null);
const handleRemark = (val, diffRatio, ind, remark) => {
  if (!diffRatio) return;
  let obj = val;
  obj.timePeriod = `${weekInfo[ind].year}W${weekInfo[ind].weekNumber}`;
  const { fundItemId, category, timePeriod } = obj;
  remarkData.value.fundType = category == "资金流入" ? 1 : 2;
  remarkData.value.fundItemId = fundItemId;
  remarkData.value.timePeriod = timePeriod;
  remarkData.value.timePeriodType = "week";
  remarkVisible.value = true;
  remarkValue.value = remark;
};
// const remarkSave = async (val) => {
//   console.log(val);
//   const { fundItemId, category } = remarkValue.value;
//   try {
//     console.log(2222222222222);
//     const { code, message } = await updateFundScheduleRemark({
//       fundType: category == "资金流入" ? 1 : 2,
//       fundItemId,
//       timePeriod,
//       remark: val,
//       timePeriodType: "week",
//     });
//     if (code !== 200) {
//       ElMessage.warning(message);
//       return;
//     }
//     ElMessage.success("修改成功!");
//     refresh();
//   } catch (error) {}
// };
</script>
<style lang="scss" scoped>
.vx-table {
  height: calc(100% - 40px) !important;
}
:deep(.vxe-pager) {
  display: none;
}
</style>
